package com.yc.sole.framework.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author yizuomin
 * @date 2024/1/3 10:05
 **/
public class ThumbnailUtil {

    private static final Integer DEFAULT_WIDTH = 100;
    private static final Integer DEFAULT_HEIGHT = 100;

    public static void generateThumbnail(String imagePath, String thumbnailPath, int thumbnailWidth, int thumbnailHeight) throws IOException {
        // 读取原始图片
        BufferedImage originalImage = ImageIO.read(new File(imagePath));

        // 创建缩略图
        BufferedImage thumbnail = new BufferedImage(thumbnailWidth, thumbnailHeight, BufferedImage.TYPE_INT_RGB);

        // 绘制缩略图
        Graphics2D graphics2D = thumbnail.createGraphics();
        graphics2D.drawImage(originalImage, 0, 0, thumbnailWidth, thumbnailHeight, null);
        graphics2D.dispose();

        // 输出缩略图到文件
        ImageIO.write(thumbnail, "JPEG", new File(thumbnailPath));
    }

    public static void generateThumbnail(InputStream imagInputStream, String thumbnailPath, int thumbnailWidth, int thumbnailHeight) throws IOException {
        // 读取原始图片
        BufferedImage originalImage = ImageIO.read(imagInputStream);

        // 创建缩略图
        BufferedImage thumbnail = new BufferedImage(thumbnailWidth, thumbnailHeight, BufferedImage.TYPE_INT_RGB);

        // 绘制缩略图
        Graphics2D graphics2D = thumbnail.createGraphics();
        graphics2D.drawImage(originalImage, 0, 0, thumbnailWidth, thumbnailHeight, null);
        graphics2D.dispose();

        // 输出缩略图到文件
        ImageIO.write(thumbnail, "JPEG", new File(thumbnailPath));
    }

    public static void generateThumbnail(String imagePath, String thumbnailPath) throws IOException {
        generateThumbnail(imagePath, thumbnailPath, DEFAULT_WIDTH, DEFAULT_HEIGHT);
    }

    public static void generateThumbnail(InputStream inputStream, String thumbnailPath) throws IOException {
        generateThumbnail(inputStream, thumbnailPath, DEFAULT_WIDTH, DEFAULT_HEIGHT);
    }
}
